package com.sixbro.authorization.security.exception;

import com.sixbro.common.domain.ApiResponse;
import com.sixbro.common.domain.ApiResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 17:35
 */
@Slf4j
@RestControllerAdvice
public class OAuth2ExceptionHandler {

    /**
     * 用户不存在
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public ApiResponse handleUsernameNotFoundException(UsernameNotFoundException e) {
        return ApiResponse.failed(ApiResponseCode.USER_NOT_EXIST);
    }

    /**
     * 用户名和密码异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidGrantException.class)
    public ApiResponse handleInvalidGrantException(InvalidGrantException e) {
        return ApiResponse.failed(ApiResponseCode.USERNAME_OR_PASSWORD_ERROR);
    }


    /**
     * 账户异常(禁用、锁定、过期)
     *
     * @param e
     * @return
     */
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public ApiResponse handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return ApiResponse.failed(e.getMessage());
    }

    @ExceptionHandler(value = OAuth2Exception.class)
    public ApiResponse<?> handleOauth2(OAuth2Exception e) {
        return ApiResponse.failed(e.getMessage());
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public ApiResponse<?> authenticationException(OAuth2Exception e) {
        return ApiResponse.failed(e.getMessage());
    }
}
